package com.zsk.shop.api.pay.ali.api;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.zsk.shop.api.pay.common.bean.PayOrder;
import com.zsk.shop.api.pay.common.bean.result.PayException;
import com.zsk.shop.api.pay.common.exception.PayErrorException;
import com.zsk.shop.common.constant.Constant;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopOrder;
import com.zsk.shop.service.ShopOrderService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.tools.Tool;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * 统一转账
 *
 * @author Administrator
 */
@Component
public class FundTransUniTransfer {

    @Autowired
    private Environment environment;
    @Resource
    private ShopOrderService orderService;

    private static Logger log = LoggerFactory.getLogger(FundTransUniTransfer.class);

    /**
     * 支付宝打款到个人的接口（直接提现）
     *
     * @param orderNo
     * @param price
     * @param aliPayAccount
     * @param trueName
     * @param remark
     * @return 提现失败原因
     * @throws AlipayApiException
     */
    public AlipayFundTransUniTransferResponse aliTransfer(String orderNo, BigDecimal price, String aliPayAccount,
                                                          String trueName, String remark) throws AlipayApiException {
        AlipayClient alipayClient = createClient();
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\"" + orderNo + "\"," +
                "\"trans_amount\":" + price + "," +
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +
                "\"order_title\":\"用户提现\"," +
                "\"payee_info\":{" +
                "\"identity\":\"" + aliPayAccount + "\"," +
                "\"identity_type\":\"ALIPAY_LOGON_ID\"," +
                "\"name\":\"" + trueName + "\"" +
                "}," +
                "\"remark\":\"" + remark + "\"," +
                "\"business_params\":\"{\\\"payer_show_name\\\":\\\"杭州惠视云联网络科技有限公司\\\"}\"" +
                "}");
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        if (response.getCode().equals("10000")) {
            return null;
        } else {
            return response;
        }
    }

    /**
     * 支付宝生成订单
     *
     * @param payOrder
     * @return
     * @throws AlipayApiException
     */
    public String createOrder(PayOrder payOrder) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", environment.getProperty("pay.ali.app.appId"), environment.getProperty("pay.ali.app.keyPrivate"),"json","GBK",environment.getProperty("pay.ali.app.alipayPublicKey"),"RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payOrder.getOutTradeNo());
        bizContent.put("total_amount", payOrder.getPrice());
        bizContent.put("subject", "ZHISHANGKE");
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
        request.setNotifyUrl(environment.getProperty("pay.ali.app.notifyUrl"));
        request.setBizContent(bizContent.toString());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理。
            System.out.println(response.getBody());
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "支付失败";
    }

    /**
     * 网页支付 生产订单
     * @param httpRequest
     * @param httpResponse
     * @param payOrder
     * @throws AlipayApiException
     */
    public void createPcOrder(HttpServletRequest httpRequest, HttpServletResponse httpResponse, PayOrder payOrder) throws AlipayApiException, IOException {
        String orderNo = payOrder.getOutTradeNo();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", environment.getProperty("pay.ali.app.appId"), environment.getProperty("pay.ali.app.keyPrivate"),"json","GBK",environment.getProperty("pay.ali.app.alipayPublicKey"),"RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(environment.getProperty("pay.ali.app.notifyUrl"));
        request.setReturnUrl(environment.getProperty("pay.ali.app.returnUrl"));
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", payOrder.getPrice());
        if (!Constant.isProd()) {
            bizContent.put("total_amount", 0.01);
        }
        bizContent.put("subject", "ZHISHANGKE");
        bizContent.put("product_code", "QUICK_WAP_WAY");
        bizContent.put("quit_url", environment.getProperty("pay.ali.app.quitUr"));
        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
        String form = "";
        try {
            //调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
            log.info(JSON.toJSONString(form));
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        //直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }


    /**
     * 支付宝退款
     * @param tradeNo
     * @param totalAmount
     * @return
     * @throws AlipayApiException
     */
    public String refund(String tradeNo, BigDecimal totalAmount) throws AlipayApiException {
        String msg = null;
        AlipayClient alipayClient = createClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", tradeNo);
        bizContent.put("refund_amount", totalAmount);
        bizContent.put("out_request_no", "HZ01RF001");

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return msg;
        } else {
            System.out.println("调用失败");
            return "退款失败";
        }
    }


    /**
     * 构造client
     *
     * @return
     * @throws AlipayApiException
     */
    public DefaultAlipayClient createClient() throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        certAlipayRequest.setAppId(environment.getProperty("pay.ali.app.appId"));
        certAlipayRequest.setPrivateKey(environment.getProperty("pay.ali.app.keyPrivate"));
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //应用公钥证书路径（app_cert_path 文件绝对路径）
        certAlipayRequest.setCertPath(environment.getProperty("pay.ali.app.publicKeyCert"));
        //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
        certAlipayRequest.setAlipayPublicCertPath(environment.getProperty("pay.ali.app.aliPayPublicKeyCert"));
        //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
        certAlipayRequest.setRootCertPath(environment.getProperty("pay.ali.app.aliPayRootCert"));
        return new DefaultAlipayClient(certAlipayRequest);
    }

}
